package org.linlinjava.litemall.admin.service.order_manage;

import cn.com.ejiakanghu.core.utils.LngLatUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.linlinjava.litemall.admin.dto.LbmHospitalDto;
import org.linlinjava.litemall.admin.form.StoreAddForm;
import org.linlinjava.litemall.admin.form.StoreListForm;
import org.linlinjava.litemall.admin.vo.order_manage.StoreDetailVo;
import org.linlinjava.litemall.core.config.BizException;
import org.linlinjava.litemall.core.util.InventoryUtil;
import org.linlinjava.litemall.db.config.CenterServerAddress;
import org.linlinjava.litemall.db.config.ServerAddress;
import org.linlinjava.litemall.db.jsonfield.LitemallGoodsProductSpecification;
import org.linlinjava.litemall.db.vo.store.RfidRecordListVo;
import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.dao.order_manage.BackendGoodsMapper;
import org.linlinjava.litemall.db.vo.store.AddGoodsListVo;
import org.linlinjava.litemall.db.vo.store.GoodsListVo;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.dao.order_manage.BackendStoreMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.vo.order_manage.BackendStoreListVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AgedmallShopStoreService {
    private Logger logger = LoggerFactory.getLogger(AgedmallShopStoreService.class);
    @Resource
    private AgedmallStoreMapper agedmallStoreMapper;
    @Resource
    private AgedmallBusiAdminMapper agedmallBusiAdminMapper;
    @Resource
    private BackendStoreMapper backendStoreMapper;
    @Resource
    private AgedmallStoreGoodsMapper agedmallStoreGoodsMapper;
    @Resource
    private AgedmallRfidGoodsProductMapper agedmallRfidGoodsProductMapper;
    @Resource
    private AgedmallStoreGoodsProductMapper agedmallStoreGoodsProductMapper;
    @Resource
    private BackendGoodsMapper backendGoodsMapper;
    @Resource
    private AgedmallRfidGoodsProductRecordMapper agedmallRfidGoodsProductRecordMapper;
    @Resource
    private AgedmallStoreHospitalMapper agedmallStoreHospitalMapper;
    @Resource
    private AgedmallDeliveryManInfoMapper agedmallDeliveryManInfoMapper;
    @Resource
    private AgedmallAnnouncerBaseInfoMapper agedmallAnnouncerBaseInfoMapper;
    @Resource
    private AgedmallGoodsEquMapper agedmallGoodsEquMapper;
    @Autowired
    private InventoryUtil inventoryUtil;
    @Resource
    private ServerAddress serverAddress;

    public Object storeList(Integer busiId, StoreListForm storeListForm){
        PageHelper.startPage(storeListForm.getPage(), storeListForm.getLimit());
        List<BackendStoreListVo> storeListVos = backendStoreMapper.storeList(busiId, storeListForm.getProvince(),
                                                                            storeListForm.getCity(), storeListForm.getArea(),
                                                                            storeListForm.getSearchKey());
        return ResponseUtil.okList(storeListVos);
    }

    @Transactional
    public Object addStore(Integer busiId, StoreAddForm storeAddForm){
        // 门店是否重复
        AgedmallStoreExample agedmallStoreExample = new AgedmallStoreExample();
        AgedmallStoreExample.Criteria criteria =agedmallStoreExample.createCriteria().andDeletedEqualTo((byte)0)
                .andStoreNameEqualTo(storeAddForm.getStoreName());
        if (null != storeAddForm.getStoreId()) {
            criteria.andIdNotEqualTo(storeAddForm.getStoreId());
        }
        AgedmallStore agedmallStore = agedmallStoreMapper.selectOneByExample(agedmallStoreExample);
        if (null != agedmallStore) {
            return ResponseUtil.fail("门店名称已存在请重新输入");
        }


        //将百度的经纬度转换为腾讯的经纬度进行存储
        logger.debug("店铺数据更新百度经纬度转腾讯:{},{},{},{}", busiId, storeAddForm.getStoreName(), storeAddForm.getLng(), storeAddForm.getLat());

        AgedmallStore store = new AgedmallStore();
        store.setBusiId(busiId);
        store.setStoreName(storeAddForm.getStoreName());
        store.setUserName(storeAddForm.getAdministrators());
        store.setPhone(storeAddForm.getContactInformation());
        store.setBusinessTime(storeAddForm.getBusinessHours());
        store.setWorkWeek(storeAddForm.getWorkWeek());
        store.setThirdLogisticsName(storeAddForm.getLogisticsName());
        store.setThirdLogisticsPhone(storeAddForm.getLogisticsInfo());
        store.setProvinceId(storeAddForm.getProvinceId());
        store.setProvinceName(storeAddForm.getProvinceName());
        store.setCityId(storeAddForm.getCityId());
        store.setCityName(storeAddForm.getCityName());
        store.setAreaId(storeAddForm.getAreaId());
        store.setAreaName(storeAddForm.getAreaName());
        store.setAddressDetail(storeAddForm.getDetailAddress());
        store.setSupportSelfDelivery(storeAddForm.getSupportSelfDelivery());
        store.setLng(storeAddForm.getLng());
        store.setLat(storeAddForm.getLat());
        store.setDistributionRange(storeAddForm.getDistributionRange());
        store.setDistributionMode(storeAddForm.getDistributionMode());
        store.setDeliveryMode(storeAddForm.getDeliveryMode());
        store.setMaintainMode(storeAddForm.getMaintainMode());
        store.setStoreType(storeAddForm.getStoreType());

        if (null == storeAddForm.getStoreId()) {
            store.setAddTime(LocalDateTime.now());
            store.setUpdateTime(LocalDateTime.now());
            store.setDeleted((byte)0);
            agedmallStoreMapper.insertSelective(store);
        } else {
            store.setId(storeAddForm.getStoreId());
            store.setUpdateTime(LocalDateTime.now());
            agedmallStoreMapper.updateByPrimaryKeySelective(store);
        }

        // 保存门店和医院关系
        LbmHospitalDto lbmHospitalDto = new LbmHospitalDto(store);
        if (null == storeAddForm.getStoreId()) {
            Long hospitalId = addHospital(lbmHospitalDto);
            AgedmallStoreHospital storeHospital = new AgedmallStoreHospital();
            storeHospital.setStoreId(store.getId());
            storeHospital.setHospitalId(hospitalId);
            storeHospital.setAddTime(LocalDateTime.now());
            agedmallStoreHospitalMapper.insertSelective(storeHospital);
        } else {
            AgedmallStoreHospitalExample storeHospitalExample = new AgedmallStoreHospitalExample();
            storeHospitalExample.createCriteria().andStoreIdEqualTo(store.getId());
            AgedmallStoreHospital storeHospital = agedmallStoreHospitalMapper.selectOneByExample(storeHospitalExample);
            lbmHospitalDto.setId(storeHospital.getHospitalId());
            addHospital(lbmHospitalDto);
        }

        return ResponseUtil.ok();
    }

    private Long addHospital(LbmHospitalDto lbmHospitalDto) {
        // 调用医院服务，返回医院id
        String result = HttpRequest.post(serverAddress.getCenter()+"/admin_api/addStoreAndHospital")
                //头信息，多个头信息多次调用此方法即可
                .header(CenterServerAddress.KEY_HEADER_STRING,CenterServerAddress.KEY_SECUREUTIL_MD5)
                .body(JSON.toJSONString(lbmHospitalDto))
                .timeout(50000)//超时，毫秒
                .execute().body();
        JSONObject jsonObject = JSON.parseObject(result);
        int code = jsonObject.getIntValue("code");
        String msg = jsonObject.getString("msg");
        if (0 != code) {
            throw new BizException(msg);
        }
        Long data =jsonObject.getLong("data") ;
        return data;
    }

    private boolean delHospital(Long hospitalId) {
        // 调用另一服务，返回医院id
        String result = HttpRequest.post(serverAddress.getCenter()+"/admin_api/delStoreAndHospital/" + hospitalId)
                //头信息，多个头信息多次调用此方法即可
                .header(CenterServerAddress.KEY_HEADER_STRING,CenterServerAddress.KEY_SECUREUTIL_MD5)
                .timeout(50000)//超时，毫秒
                .execute().body();
        JSONObject jsonObject = JSON.parseObject(result);
        boolean success = jsonObject.getIntValue("code") == 0;
        return success;
    }

    @Transactional
    public Object delStore(@RequestParam List<Long> storeIds){
        for (Long storeId : storeIds) {
            AgedmallAnnouncerBaseInfoExample announcerBaseInfoExample = new AgedmallAnnouncerBaseInfoExample();
            announcerBaseInfoExample.createCriteria().andDeletedEqualTo(false)
                    .andStoreIdEqualTo(storeId.intValue());
            List<AgedmallAnnouncerBaseInfo> announcerBaseInfos = agedmallAnnouncerBaseInfoMapper.selectByExample(announcerBaseInfoExample);
            if (CollectionUtils.isNotEmpty(announcerBaseInfos)) {
                throw new BizException("门店下存在播报机，不可删除");
            }
            // 删除门店员工关系
            List<Integer> staffIds = backendStoreMapper.getStaffIds(storeId);
            employeeDel(storeId+"", staffIds);
        }

        AgedmallStoreExample agedmallStoreExample = new AgedmallStoreExample();
        agedmallStoreExample.createCriteria().andDeletedEqualTo((byte)0)
                .andIdIn(storeIds);
        agedmallStoreMapper.logicalDeleteByExample(agedmallStoreExample);
        // 删除门店医院关联表
        AgedmallStoreHospitalExample storeHospitalExample = new AgedmallStoreHospitalExample();
        storeHospitalExample.createCriteria()
                .andStoreIdIn(storeIds);
        List<AgedmallStoreHospital> storeHospitals = agedmallStoreHospitalMapper.selectByExample(storeHospitalExample);
        for (AgedmallStoreHospital storeHospital : storeHospitals) {
            delHospital(storeHospital.getHospitalId());
        }
        agedmallStoreHospitalMapper.deleteByExample(storeHospitalExample);

        return ResponseUtil.ok();
    }

    public Object storeDetail(Long storeId){
        StoreDetailVo storeDetailVo = new StoreDetailVo();
        AgedmallStore store = agedmallStoreMapper.selectByPrimaryKey(storeId);
        if (null != store) {
            storeDetailVo.setId(store.getId().intValue());
            storeDetailVo.setStoreName(store.getStoreName());
            storeDetailVo.setUserName(store.getUserName());
            storeDetailVo.setPhone(store.getPhone());
            storeDetailVo.setBusinessTime(store.getBusinessTime());
            storeDetailVo.setWorkWeek(store.getWorkWeek());
            storeDetailVo.setThirdLogisticsName(store.getThirdLogisticsName());
            storeDetailVo.setThirdLogisticsPhone(store.getThirdLogisticsPhone());
            storeDetailVo.setSupportSelfDelivery(store.getSupportSelfDelivery());
            storeDetailVo.setProvinceId(store.getProvinceId());
            storeDetailVo.setCityId(store.getCityId());
            storeDetailVo.setAreaId(store.getAreaId());
            storeDetailVo.setAddressDetail(store.getAddressDetail());
            storeDetailVo.setAddress(store.getAddressDetail());
            storeDetailVo.setLng(store.getLng());
            storeDetailVo.setLat(store.getLat());
            storeDetailVo.setDistributionRange(store.getDistributionRange());
            storeDetailVo.setDistributionMode(store.getDistributionMode());
            storeDetailVo.setDeliveryMode(store.getDeliveryMode());
            storeDetailVo.setMaintainMode(store.getMaintainMode());
            storeDetailVo.setStoreType(store.getStoreType());

        }
        return ResponseUtil.ok(storeDetailVo);
    }

    public Object commodityDetailList(Long storeId, String state, Integer page, Integer limit){
        PageHelper.startPage(page, limit);
        List<GoodsListVo> list = backendStoreMapper.commodityDetailList(storeId, state);
        list.stream().forEach(p ->{
            // 合并显示规格
            List<LitemallGoodsProductSpecification> specificationList = JSON.parseArray(p.getGoodsSpec(), LitemallGoodsProductSpecification.class);
            String spec = "";
            if (CollectionUtils.isNotEmpty(specificationList)) {
                for (LitemallGoodsProductSpecification specification : specificationList) {
                    spec += "," + specification.getInfoName() + ":" + specification.getName();
                }
            }
            p.setGoodsSpec(spec.replaceFirst(",", ""));
            // 获取库存
            // 门店
            if (null != p.getGoodsStock() && p.getGoodsStock() >= 0) {
                p.setStoreStock(inventoryUtil.get(p.getStoreId(), InventoryUtil.TYPE_STORE, InventoryUtil.STOCK_STORE,
                                                    p.getGoodsId(), p.getGoodsProductId()));
            }
            // 软链
            if (null != p.getChainLock() && p.getChainLock() > 0) {
                p.setChainStock(inventoryUtil.get(p.getStoreId(), InventoryUtil.TYPE_STORE, InventoryUtil.STOCK_SOFTCHAIN,
                        p.getGoodsId(), p.getGoodsProductId()));
            }
            // 医柜
            if (null != p.getCabinetLock() && p.getCabinetLock() > 0) {
                p.setCabinetStock(inventoryUtil.get(p.getStoreId(), InventoryUtil.TYPE_STORE, InventoryUtil.STOCK_CABINET,
                        p.getGoodsId(), p.getGoodsProductId()));
            }
        });
        return ResponseUtil.okList(list);
    }

    public Object commodityDetailAddDialogList(Integer busiId, String classIfication1, String classIfication2, String type,
                                               String keySearch, Integer page, Integer limit){
        PageHelper.startPage(page, limit);
        List<AddGoodsListVo> list = backendStoreMapper.commodityDetailAddDialogList(busiId, classIfication1, classIfication2, type, keySearch);
        return ResponseUtil.okList(list);
    }

    public Object commodityDetailCancel(List<Long> storeGoodsIds){
        // 取消rfid商品和门店关联
        for (Long storeGoodsId : storeGoodsIds) {
            AgedmallStoreGoods agedmallStoreGoods = agedmallStoreGoodsMapper.selectByPrimaryKey(storeGoodsId);
            if (null != agedmallStoreGoods) {
                backendGoodsMapper.updateStoreGoodsRfid(agedmallStoreGoods.getGoodsId(), agedmallStoreGoods.getStoreId());
            }
        }
        //  取消商品和门店关联
        AgedmallStoreGoodsExample agedmallStoreGoodsExample = new AgedmallStoreGoodsExample();
        agedmallStoreGoodsExample.createCriteria()
                .andIdIn(storeGoodsIds);
        agedmallStoreGoodsMapper.deleteByExample(agedmallStoreGoodsExample);
        // 取消商品规格和门店关联
        AgedmallStoreGoodsProductExample agedmallStoreGoodsProductExample = new AgedmallStoreGoodsProductExample();
        agedmallStoreGoodsProductExample.createCriteria().andDeletedEqualTo(false).andStoreGoodsIdIn(storeGoodsIds);
        agedmallStoreGoodsProductMapper.deleteByExample(agedmallStoreGoodsProductExample);

        return ResponseUtil.ok();
    }

    public Object commodityDetailSetting(Long storeGoodsId, Long maintainTemplateId){
        AgedmallStoreGoods agedmallStoreGoods = new AgedmallStoreGoods();
        agedmallStoreGoods.setId(storeGoodsId);
        agedmallStoreGoods.setMaintainTemplateId(maintainTemplateId);
        agedmallStoreGoodsMapper.updateByPrimaryKeySelective(agedmallStoreGoods);
        return ResponseUtil.ok();
    }

    public Object commodityDetailEquipment(Long storeId, Long commodityId, Integer page, Integer limit){
        PageHelper.startPage(page, limit);

        AgedmallGoodsEquExample example = new AgedmallGoodsEquExample();
        example.createCriteria().andDeletedEqualTo((byte)0)
                .andStoreIdEqualTo(storeId)
                .andGoodsProductIdEqualTo(commodityId)
                .andTypeEqualTo(0);
        List<AgedmallGoodsEqu> goodsEqus = agedmallGoodsEquMapper.selectByExample(example);
        return ResponseUtil.okList(goodsEqus);
    }

    public Object commodityDetailEquipmentDetail(Long equipmentId, Integer page, Integer limit){
        PageHelper.startPage(page, limit);

        List<RfidRecordListVo> list = backendStoreMapper.commodityDetailEquipmentDetail(equipmentId);
        return ResponseUtil.okList(list);
    }

    public Object employeeDel(String storeId, List<Integer> staffIds){
        for (Integer staffId : staffIds) {
            AgedmallDeliveryManInfo deliveryManInfo = agedmallDeliveryManInfoMapper.selectByPrimaryKey(staffId);
            if (null != deliveryManInfo) {
                String storeIds = deliveryManInfo.getStoreId();
                if (StringUtils.isNotEmpty(storeIds)) {
                    String[] arr = storeIds.split(",");
                    List<String> list = Arrays.asList(arr);
                    List<String> storeList = new ArrayList<>(list);
                    storeList.remove(storeId);
                    String newStoreIds = storeList.stream().collect(Collectors.joining(","));
                    deliveryManInfo.setStoreId(newStoreIds);
                    agedmallDeliveryManInfoMapper.updateByPrimaryKeySelective(deliveryManInfo);
                }
            }
        }
        return ResponseUtil.ok();
    }

    public Object commodityDetailGetSetting(Integer storeGoodsId){
        AgedmallStoreGoods storeGoods = agedmallStoreGoodsMapper.selectByPrimaryKey(storeGoodsId.longValue());
        if (null == storeGoods) {
            return ResponseUtil.badArgumentValue();
        }
        return ResponseUtil.ok(new HashMap<String, Long>(){{put("maintainTemplateId", storeGoods.getMaintainTemplateId());}});
    }
}
